package com.vercon.commonmirror.apng;


import android.content.Context;

import com.github.penfeizhou.animation.apng.decode.APNGDecoder;
import com.github.penfeizhou.animation.decode.FrameSeqDecoder;
import com.github.penfeizhou.animation.loader.AssetStreamLoader;
import com.github.penfeizhou.animation.loader.FileLoader;
import com.github.penfeizhou.animation.loader.Loader;
import com.github.penfeizhou.animation.loader.ResourceStreamLoader;

import skin.support.utils.SkinPreference;


/**
 * Created by csh on 2021/4/20
 * 加载APNG动态图片
 */
public class APNGDrawable extends com.github.penfeizhou.animation.FrameAnimationDrawable<APNGDecoder> {

    public APNGDrawable(Loader provider) {
        super(provider);
    }

    public APNGDrawable(APNGDecoder decoder) {
        super(decoder);
    }

    @Override
    protected APNGDecoder createFrameSeqDecoder(Loader streamLoader, FrameSeqDecoder.RenderListener listener) {
        return new APNGDecoder(streamLoader, listener);
    }


    public static APNGDrawable fromAsset(Context context, String assetPath) {
        String path =  isContainAssets(context,assetPath);
        AssetStreamLoader assetStreamLoader = new AssetStreamLoader(context,path);
        return new APNGDrawable(assetStreamLoader);
    }

    //不根据当前主题皮肤去获取动图
    public static APNGDrawable fromAssetNoSkin(Context context, String assetPath) {
        AssetStreamLoader assetStreamLoader = new AssetStreamLoader(context,assetPath);
        return new APNGDrawable(assetStreamLoader);
    }

    public static APNGDrawable fromFile(String filePath) {
        FileLoader fileLoader = new FileLoader(filePath);
        return new APNGDrawable(fileLoader);
    }

    public static APNGDrawable fromResource(Context context, int resId) {
        ResourceStreamLoader resourceStreamLoader = new ResourceStreamLoader(context, resId);
        return new APNGDrawable(resourceStreamLoader);
    }


    //这个是根据换肤的主题去获取相应的动画
    public static String isContainAssets(Context context, String path) {
        try {

            //获取当前主题对应的动态图片路径
            String[] pathList = path.split("/");//获取原主题的动画路径的文件名
            String[] fileLists = context.getAssets().list("APNG_"+ SkinPreference.getInstance().getSkinName());//获取S主题的动画路径下的所有文件名  例：APNG_gold
            if (fileLists == null || fileLists.length == 0) {
                //若无文件，返回原主题的动画路径的文件名
                return path;
            }
            //判断s主题文件夹内是否有替换的文件
            for (int i = 0; i < fileLists.length; i++) {
                if (fileLists[i].equals(pathList[1])) {
                    //有替换的文件，返回当前主题路径
                    return "APNG_"+SkinPreference.getInstance().getSkinName() +"/" + pathList[1];  //APNG_gold
                }
            }
            return path; //无替换的文件，返回原路径

        } catch (Exception e) {
            return path;//无替换的文件，返回原路径
        }
    }

}
